package com.czk.track;

import java.util.Stack;

/**
 * 链路追踪
 *
 * @Author:ChenZhangKun
 * @Date: 2021/8/10 9:41
 */
public class TrackManager {
    private static final ThreadLocal<Stack<String>> track = new ThreadLocal<>();

    public static String createSpan() {
        Stack<String> stack = track.get();
        if (stack == null) {
            stack = new Stack<>();
            track.set(stack);
        }
        String linkId;
        // 栈为空
        if (stack.isEmpty()) {
            // 拿到线程
            linkId = TrackContext.get();
            if (linkId == null) {
                linkId = "nvl";
                TrackContext.setLinkedId(linkId);
            }
        } else {
            linkId = stack.peek();
            TrackContext.setLinkedId(linkId);
        }
        return linkId;
    }

    public static String createEntrySpan() {
        String span = createSpan();
        Stack<String> stack = track.get();
        stack.push(span);
        return span;
    }

    public static String getExitSpan() {
        Stack<String> stack = track.get();
        if (stack == null || stack.isEmpty()) {
            TrackContext.clear();
            return null;
        }
        return stack.pop();
    }

    public static String getCurrentSpan() {
        Stack<String> stack = track.get();
        if (stack == null || stack.isEmpty()) {
            return null;
        }
        return stack.peek();
    }
}
